package com.czy.owner.ui.physicalorder;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.czy.owner.R;
import com.czy.owner.adapter.SelectStoreAdapter;
import com.czy.owner.api.SelectStoreApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.SelectStoreModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.MyLoadView;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.hotshop.ServiceStoreSearchActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.czy.owner.ui.physicalorder.ConfirmOrderActivity.TRANSMISSION_GOODS_TYPE_KEY;

public class SelectServiceStoreFragment extends BaseFragment implements android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener, RecyclerArrayAdapter.OnLoadMoreListener {
    @BindView(R.id.ll_search_store_name)
    LinearLayout llSearchStoreName;

    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    private SelectStoreAdapter adapter;
    private int page = 1;
    private Handler handler = new Handler();
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private MyLoadView myLoadView;
    //标识，用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFirstLoc = true;
    private final static int SELECT_STORE_TYPE = 0x11;
    private boolean hideServicePrice = false;
    private ConfirmOrderActivity.ConfirmOrderJumpType confirmOrderJumpType = ConfirmOrderActivity.ConfirmOrderJumpType.CART;
    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_select_service_store;
    }

    @Override
    protected void initInjector() {
        boolean hasArgument = getArguments() == null ? false:getArguments().containsKey("hideSearchBar");
        if(hasArgument && getArguments().getBoolean("hideSearchBar")){
            llSearchStoreName.setVisibility(View.GONE);
            hideServicePrice = true ;
        }
    }

    @Override
    protected void initViews() {
        if("0".equals(getActivity().getIntent().getStringExtra("goodsId"))){
            return;
        }
        if(getActivity().getIntent().getExtras().containsKey(TRANSMISSION_GOODS_TYPE_KEY)){
            confirmOrderJumpType = (ConfirmOrderActivity.ConfirmOrderJumpType) getActivity().getIntent().getSerializableExtra(TRANSMISSION_GOODS_TYPE_KEY);
        }
        initLoc();
        myLoadView = new MyLoadView(getActivity(), "正在加载");
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(adapter = new SelectStoreAdapter(getActivity(), hideServicePrice));
        recyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore, new RecyclerArrayAdapter.OnNoMoreListener() {
            @Override
            public void onNoMoreShow() {
                // adapter.resumeMore();
            }

            @Override
            public void onNoMoreClick() {
                adapter.resumeMore();
            }
        });

        adapter.setError(R.layout.view_error_net, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();

            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();

            }
        });
        recyclerView.setRefreshListener(this);
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<SelectStoreModel>() {
            @Override
            public void onItemClick(View view,int position, SelectStoreModel o) {
                Intent intent = new Intent();
                intent.putExtra("backType",0);
                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, o);
                getActivity().setResult(getActivity().RESULT_OK, intent);
                getActivity().finish();
            }
        });




    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(getActivity())) {
                    adapter.pauseMore();
                    recyclerView.showError();
                    return;
                }
                page = 1;
                getStoreList(longItude, latItude);

            }
        }, 1000);
    }
    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(getActivity())) {
                    adapter.pauseMore();
                    recyclerView.showError();
                    return;
                }
                page++;
                getStoreList(longItude, latItude);

            }
        }, 1000);
    }

    private void setSelectStoreList(List<SelectStoreModel> list) {
        if (page == 1 && list.size() == 0) {
            recyclerView.setEmptyView(R.layout.view_empty_common);
            recyclerView.showEmpty();
        }
        if (list.size() < 10) {
            adapter.stopMore();
        }
        adapter.addAll(list);
    }

    private double longItude;
    private double latItude;
    //  定位回调监听事件
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    longItude = amapLocation.getLongitude();//获取经度
                    latItude = amapLocation.getLatitude();//获取纬度
                    amapLocation.getAccuracy();//获取精度信息

                    if (isFirstLoc) {
                        isFirstLoc = false;
                        MyLog.e("asus",isFirstLoc+"");
                        getStoreList(longItude, latItude);

                    }
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("qwe", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    private void getStoreList(double longItude, double latItude) {
        if (page == 1) {
            myLoadView.ShowLoadView();
            adapter.clear();
        }

        SelectStoreApi selectStoreApi = new SelectStoreApi(new HttpOnNextListener<List<SelectStoreModel>>() {
            @Override
            public void onNext(List<SelectStoreModel> list) {
                myLoadView.CancleLoadView();
                setSelectStoreList(list);

            }
            @Override
            public void onError(Throwable e) {
                myLoadView.CancleLoadView();
                super.onError(e);
                PhoneUtils.ShowToastMessage(getActivity(), e.getMessage());
            }

        }, (RxAppCompatActivity)(getContext()));
        selectStoreApi.setSession(UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
        selectStoreApi.setGprsX(String.valueOf(longItude));
        selectStoreApi.setGprsY(String.valueOf(latItude));
        selectStoreApi.setPage(page + "");
        selectStoreApi.setSize("10");
        selectStoreApi.setGoodsId(getActivity().getIntent().getStringExtra("goodsId"));
        if(confirmOrderJumpType == ConfirmOrderActivity.ConfirmOrderJumpType.WORK){
            selectStoreApi.setType("manual");
        }
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(selectStoreApi);
    }

    //定位初始化控件配置

    private void initLoc() {
        locationClient = new AMapLocationClient(getActivity());
        //设置定位回调监听
        locationClient.setLocationListener(mAMapLocationListener);
        //初始化定位参数
        locationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        locationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        locationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        locationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        locationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        locationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        locationClient.setLocationOption(locationOption);
        //启动定位
        locationClient.startLocation();

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != locationClient) {
            locationClient.stopLocation();
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }


    @OnClick(R.id.ll_search_store_name)
    public void onViewClicked() {
        Intent intent = new Intent(getActivity(), ServiceStoreSearchActivity.class);
        intent.putExtra("goodsId", getActivity().getIntent().getStringExtra("goodsId"));
        startActivityForResult(intent, SELECT_STORE_TYPE);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_STORE_TYPE && resultCode == getActivity().RESULT_OK) {
            Intent intent = new Intent();
            intent.putExtra("backType",0);
            intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY));
            getActivity().setResult(getActivity().RESULT_OK, intent);
            getActivity().finish();
        }
    }


}